package com.zx.bean;

import com.zx.annotation.Bean;

import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import com.zx.annotation.Di;
import org.junit.jupiter.api.Test;

public class AnnotationApplicationContext implements ApplicationContext {
    //创建map集合，放bean对象
    private Map<Class, Object> beanFactory = new HashMap<>();
    private static String rootPath;
    @Override
    public Object getBean(Class clazz) {
        return beanFactory.get(clazz);
    }
    //设置包扫描规则
    //当前包及其子包，哪个类有@Bean注解，把这个类通过反射实例化
//    public static void debug(String basePackage){
    public AnnotationApplicationContext(String basePackage) {
        try {
//            String packageDirName = basePackage.replaceAll("\\.", "\\\\");
            String packageDirName = basePackage.replaceAll("\\.", "/");
            Enumeration<URL> dirs =Thread.currentThread().getContextClassLoader().getResources(packageDirName);
            while (dirs.hasMoreElements()) {
                URL url = dirs.nextElement();
                String filePath = URLDecoder.decode(url.getFile(),"utf-8");
                rootPath = filePath.substring(0, filePath.length()-packageDirName.length());
                loadBean(new File(filePath));
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //属性注入
        loadDi();
    }

//    @Test
//    public void tt() {
//        debug("com.zx");
//    }


    private  void loadBean(File fileParent) {
        if (fileParent.isDirectory()) {
            File[] childrenFiles = fileParent.listFiles();
            if(childrenFiles == null || childrenFiles.length == 0){
                return;
            }
            for (File child : childrenFiles) {
                if (child.isDirectory()) {
                    //如果是个文件夹就继续调用该方法,使用了递归
                    loadBean(child);
                } else {
                    //通过文件路径转变成全类名,第一步把绝对路径部分去掉
                    String pathWithClass = child.getAbsolutePath().substring(rootPath.length() - 1);
                    //选中class文件
                    if (pathWithClass.contains(".class")) {
                        //    com.zx.dao.UserDao
                        //去掉.class后缀，并且把 \ 替换成 .
//                        String fullName = pathWithClass.replaceAll("\\\\", ".").replace(".class", "");
                        String fullName = pathWithClass.replaceAll("/", ".").replace(".class", "").substring(1);
                        try {
                            Class<?> aClass = Class.forName(fullName);
                            //把非接口的类实例化放在map中
                            if(!aClass.isInterface()){
                                Bean annotation = aClass.getAnnotation(Bean.class);
                                if(annotation != null){
                                    Object instance = aClass.newInstance();
                                    //判断一下有没有接口
                                    if(aClass.getInterfaces().length > 0) {
                                        //如果有接口把接口的class当成key，实例对象当成value
                                        System.out.println("正在加载【"+ aClass.getInterfaces()[0] +"】,实例对象是：" + instance.getClass().getName());
                                        beanFactory.put(aClass.getInterfaces()[0], instance);
                                    }else{
                                        //如果没有接口把自己的class当成key，实例对象当成value
                                        System.out.println("正在加载【"+ aClass.getName() +"】,实例对象是：" + instance.getClass().getName());
                                        beanFactory.put(aClass, instance);
                                    }
                                }
                            }
                        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    //属性注入
    private void loadDi() {
        //实例化对象在beanFactory的map集合里面
        //1. 获取beanFactory的map集合
        for (Map.Entry<Class, Object> entry : beanFactory.entrySet()) {
            //2.获取map集合每个value,就是咱们放在容器的对象
            Object obj = entry.getValue();
            Class<?> aClass = obj.getClass();//获取对象Class
            //3.获取每个对象的所有属性的数组
            Field[] declaredFields = aClass.getDeclaredFields();
            //4.判断每个属性上面是否有@Di注解
            for (Field field : declaredFields) {
                Di annotation = field.getAnnotation(Di.class);
                //5.如果有@Di注解，把对象进行设置(注入)，即设置对象的字段值
                if (annotation != null) {
                    field.setAccessible(true);//如果为私有属性，设置为可以访问
                    try {
                        System.out.println("正在给【" + obj.getClass().getName() + "】属性【" + field.getName() + "】注入值【" + beanFactory.get(field.getType()).getClass().getName() + "】");
                        field.set(obj, beanFactory.get(field.getType()));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

//    public static void main(String[] args) {
//        ApplicationContext context = new AnnotationApplicationContext("com.zx");
//        context.getBean()
//    }
}
